function AutocorrelationFigure_Blues(A_FP1, A_FP2, A_Bckgrnd, colonySet)
%AUTOCORRELATIONFIGURE Summary of this function goes here
%   Detailed explanation goes here


tInt = colonySet{1}.exp.TimeInt;

AB = A_Bckgrnd.colAutocorrMedian;
A1 = A_FP1.Autocorr;
A2 = A_FP2.Autocorr;

A1(1) = A1(1) - AB(1); %Substract background contribution
A2(1) = A2(1) - AB(1);


plotFrame = [1 31];
%% to A1, fit a simple exponential decay
frame1_r = [1 31];
range = [];
range.b = [0.8 1.2]*mean(A1(40:60));
range.a = [0.7 1.3]*(A1(1) - mean(A1(40:60)));
range.gamma = [0.01 0.25];
range.frame = frame1_r;

cf1_ = FitShiftExp(range, A1, tInt)
ci1 = confint(cf1_);
coeff1 = coeffvalues(cf1_);

%% to A2, fit a simple exponential decay
frame2_r = [1 30];
range.b = [0.8 1.2]*mean(A2(20:30));
range.a = [0.7 1.3]*(A2(1) - mean(A2(20:30)));
range.gamma = [0.02 0.20];
range.frame = frame2_r;

cf2_ = FitShiftExp(range, A2, tInt)
ci2 = confint(cf2_);
coeff2 = coeffvalues(cf2_);


%% Renormalize A1 and A2 using fiting params
A1 = (A1 - coeff1(2))/coeff1(1);
A2 = (A2 - coeff2(2))/coeff2(1);

expDecay = @(t, gamma)(exp(-gamma*t));

lagTheo = (plotFrame(1)-1:plotFrame(2)-1)*tInt;
fitA1 = expDecay(lagTheo, coeff1(3));
fitA2 = expDecay(lagTheo, coeff2(3));

fig_h = figure('Color', [1 1 1]);
hold on;

%All data
plot(lagTheo, A2(plotFrame(1):plotFrame(2)), '.', 'markersize', 24, 'Color', [58 219 255]/255);
plot(lagTheo, A1(plotFrame(1):plotFrame(2)), 'ow', 'markersize', 8, 'Color', [3 146 178]/255, 'linewidth', 2.0);


plot(lagTheo, fitA1, '-', 'LineWidth', 3, 'Color', [3 146-30 178-30]/255)
plot(lagTheo, fitA2, '-k', 'LineWidth', 3, 'Color', [58-30 219-30 255-30]/255)

line([0 150], [1 1]*0, 'Color', 'k', 'LineStyle', ':', 'linewidth', 1)

xlim((plotFrame-1)*tInt);
ylim([-0.1 1.05]);

box on;
set(gca,'box','off')
isholdonque = ishold; 
hold on 
ax = axis; 
plot(ax(2)*[1,1],ax(3:4),'k','linewidth',0.5) 
plot(ax(1:2),ax(4)*[1,1],'k','linewidth',0.5) 
if isholdonque == 0 
hold off 
end

hleg1 = legend('Fast FP','Slow FP');
set(hleg1,'FontSize',20);
legend(hleg1, 'boxoff')

xlabel('\fontsize{18}Time (min)');
ylabel('\fontsize{18}Autocorrelation');
set(gca, 'FontSize', 16);

daspect([100 0.85 1])

end


%.........................................................................
function cf_ = FitShiftExp(range, A, tInt)

a_r = range.a;
b_r = range.b;
gamma_r = range.gamma;
frame_r = range.frame;

A = A(frame_r(1):frame_r(2))';
lag = ((frame_r(1)-1:frame_r(2)-1)*tInt)';

ft_ = fittype('ShiftedExp(t, a, b, gamma)',...
    'coefficients', {'a', 'b', 'gamma'}, 'independent', {'t'});

fo_ = fitoptions('method', 'NonlinearLeastSquares', 'Robust', 'On',...
    'Lower', [a_r(1) b_r(1) gamma_r(1)],...
    'Upper', [a_r(2) b_r(2) gamma_r(2)]);

cf_ = fit(lag, A, ft_, fo_);

end
